package top.kaoshanji.p1ch03b;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import top.kaoshanji.u1constant.FileConstant;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * 代码清单 p1ch03b-01：阻塞式客户端套接字的使用示例(保存网页内容第2种写法)
 * author kaoshanji
 * ^_^
 * create time 2025/1/8 18:36
 */
public class SocketChannelExample01 {

    private static final Logger logger = LogManager.getLogger(SocketChannelExample01.class);

    public static void main(String[] args) {
        logger.info("...代码清单 p1ch03b-01：阻塞式客户端套接字的使用示例(保存网页内容第2种写法)...");

        try (FileChannel descChannel = FileChannel.open(Paths.get(FileConstant.LOCAL_ROOT_PATH.concat("p1ch03b01.txt")), StandardOpenOption.WRITE, StandardOpenOption.CREATE);
             SocketChannel sc = SocketChannel.open(new InetSocketAddress("www.baidu.com", 80))){

            String request = "GET / HTTP/1.1\r\n\r\nHost: www.baidu.com\r\n\r\n";
            ByteBuffer header = ByteBuffer.wrap(request.getBytes(StandardCharsets.UTF_8));
            sc.write(header);

            descChannel.transferFrom(sc, 0, Integer.MAX_VALUE);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }

}
